#!/usr/bin/python3

import pandas as pd
from sklearn import preprocessing
from sklearn import cross_validation
import numpy as np
from sklearn.ensemble import RandomForestRegressor

max_reg = object
max_score = 0.0


def train(df_train):
    global max_reg
    global max_score
    df_train['year'] = pd.DatetimeIndex(df_train.datetime).year
    df_train['month'] = pd.DatetimeIndex(df_train.datetime).month
    df_train['day'] = pd.DatetimeIndex(df_train.datetime).day
    df_train['hour'] = pd.DatetimeIndex(df_train.datetime).hour
    target = df_train['count'].values
    feature = df_train.drop(['count', 'month', 'atemp', 'casual', 'registered', 'datetime'], axis=1).values
    feature_scaled = preprocessing.scale(feature)
    cv = cross_validation.ShuffleSplit(feature_scaled.shape[0], n_iter=20, test_size=0.2, random_state=None)
    for train, test in cv:
        reg = RandomForestRegressor(n_estimators=1000, min_samples_split=11, oob_score=True).fit(
            feature_scaled[train], target[train])
        print(reg.score(feature_scaled[train], target[train]), reg.score(feature_scaled[test], target[test]))
        score = reg.score(feature_scaled[test], target[test])
        if score > max_score:
            max_score = score
            max_reg = reg
    print(max_score)


def write(df_test):
    df_test['year'] = pd.DatetimeIndex(df_test.datetime).year
    df_test['month'] = pd.DatetimeIndex(df_test.datetime).month
    df_test['day'] = pd.DatetimeIndex(df_test.datetime).day
    df_test['hour'] = pd.DatetimeIndex(df_test.datetime).hour
    test = df_test.drop(['datetime', 'month', 'atemp'], axis=1)
    test_scale = preprocessing.scale(test.values)
    pre = np.array(max_reg.predict(test_scale))
    d = dict()
    date = np.array(df_test['datetime'])
    d['datetime'] = date
    ls = []
    for p in pre:
        ls.append(round(p))
    d['count'] = ls
    result = pd.DataFrame(data=d)
    result.to_csv('over.csv', index=False, sep=',')


if __name__ == '__main__':
    df_train = pd.read_csv('./train.csv')
    df_test = pd.read_csv('./test.csv')
    train(df_train)
    write(df_test)
